package com.example.orderapplication

import android.Manifest
import android.R.attr
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.widget.*
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

import com.example.orderapplication.adapter.HomeAdapter
import com.example.orderapplication.adapter.MenuAdapter
import com.example.orderapplication.bean.CategoryBean
import com.example.orderapplication.bean.Data
import com.example.orderapplication.helper.DataHelper
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
import com.yzq.zxinglibrary.encode.CodeCreator

import android.R.attr.bitmap
import android.app.Dialog

import android.graphics.BitmapFactory

import android.graphics.Bitmap
import android.view.Window
import android.view.WindowManager
import com.bumptech.glide.Glide
import com.example.orderapplication.bean.DataX


class MainActivity : AppCompatActivity() {
    private var DB: DataHelper? = null
    private val TAG = "MainActivity"
    private val REQUEST_CODE = 1024
    private lateinit var categoryBean: CategoryBean


    private val mTvTotalPrice: TextView by lazy { findViewById(R.id.tv_total_price) }
    private val mTvSettlement: TextView by lazy { findViewById(R.id.tv_settlement) }
    private val mTvKeyword: TextView by lazy { findViewById(R.id.tv_keyword) }

    private val menuList: MutableList<String> = arrayListOf()
    private val homeList: MutableList<Data> = arrayListOf()
    private var showTitle: MutableList<Int> = arrayListOf()
    private var lv_menu: ListView? = null
    private var lv_home: ListView? = null

    private var menuAdapter: MenuAdapter? = null
    private var homeAdapter: HomeAdapter? = null
    private var currentItem = 0

    private var tv_title: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestPermission()
        DB = DataHelper(this)
        initView()
        loadData()

        homeAdapter?.setOnInnerItemOnClickListener(object : HomeAdapter.InnerItemOnclickListener {
            override fun itemClick(item: Int) {
                Log.e(TAG, item.toString())
                mTvTotalPrice.text = (item + mTvTotalPrice.text.toString().toInt()).toString()
            }
        })
        homeAdapter?.setDetailsOnInnerItemOnClickListener(object :
            HomeAdapter.DetailsInnerItemOnclickListener {
            override fun DetailsitemClick(item: DataX) {
                val i = Intent(this@MainActivity, DetailsActivity::class.java)
                i.putExtra("DataX", item)
                startActivity(i)
            }

        })
        mTvKeyword.setOnClickListener {
            startActivity(Intent(this, SearchActivity::class.java))
        }
        mTvSettlement.setOnClickListener {
            if (mTvTotalPrice.text.toString().toInt() != 0) {
                val logo = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
                val bitmap =
                    CodeCreator.createQRCode("总价：" + mTvTotalPrice.text.toString(), 400, 400, logo)
                dia(bitmap)
                dia?.show()
            } else {
                Toast.makeText(this, "请先选择物品", Toast.LENGTH_SHORT).show()
            }
        }

    }

    var dia: Dialog? = null
    private fun dia(bitmap: Bitmap) {
        val context: Context = this@MainActivity
        dia = Dialog(context, R.style.edit_AlertDialog_style)
        dia!!.setContentView(R.layout.activity_start_dialog)
        val imageView = dia!!.findViewById(R.id.start_img) as ImageView
        Glide.with(context)
            .load(bitmap)
            .placeholder(R.drawable.ic_launcher_background)
            .into(imageView)
        //选择true的话点击其他地方可以使dialog消失，为false的话不会消失
        //选择true的话点击其他地方可以使dialog消失，为false的话不会消失
        dia!!.setCanceledOnTouchOutside(true) // Sets whether this dialog is

        val w: Window? = dia!!.getWindow()
        val lp: WindowManager.LayoutParams = w!!.attributes
        lp.x = 0
        lp.y = 80
        dia!!.onWindowAttributesChanged(lp)
        imageView.setOnClickListener {
            dia!!.dismiss()
        }

    }

    private fun loadData() {
        val json: String = getJson(this, "category.json")
        Log.e(TAG, json)
        categoryBean = Gson().fromJson(json, CategoryBean::class.java)
        showTitle = ArrayList()
        for (i in categoryBean.data!!.indices) {
            val dataBean: Data = categoryBean.data!![i]
            menuList.add(dataBean.moduleTitle!!)
            showTitle.add(i)
            homeList.add(dataBean)
        }
        tv_title!!.text = categoryBean.data!![0].moduleTitle
        menuAdapter!!.notifyDataSetChanged()
        homeAdapter!!.notifyDataSetChanged()
    }

    private fun initView() {
        lv_menu = findViewById(R.id.lv_menu)
        tv_title = findViewById(R.id.tv_titile)
        lv_home = findViewById(R.id.lv_home)
        menuAdapter = MenuAdapter(this, menuList)
        lv_menu!!.adapter = menuAdapter

        homeAdapter = HomeAdapter(this, homeList)
        lv_home!!.adapter = homeAdapter

        lv_menu!!.setOnItemClickListener { parent, view, position, id ->
            menuAdapter!!.setSelectItem(position)
            menuAdapter!!.notifyDataSetInvalidated()
            tv_title!!.text = menuList[position]
            lv_home!!.setSelection(showTitle[position])
        }


        lv_home!!.setOnScrollListener(object : AbsListView.OnScrollListener {
            private var scrollState = 0
            override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {
                this.scrollState = scrollState
            }

            override fun onScroll(
                view: AbsListView, firstVisibleItem: Int,
                visibleItemCount: Int, totalItemCount: Int
            ) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    return
                }
                val current = showTitle.indexOf(firstVisibleItem)
                //				lv_home.setSelection(current);
                if (currentItem != current && current >= 0) {
                    currentItem = current
                    tv_title!!.text = menuList[currentItem]
                    menuAdapter!!.setSelectItem(currentItem)
                    menuAdapter!!.notifyDataSetInvalidated()
                }
            }
        })
    }


    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:$packageName")
                startActivityForResult(intent, REQUEST_CODE)
            } else {
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    REQUEST_CODE
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 得到json文件中的内容
     *
     * @param context
     * @param fileName
     * @return
     */
    fun getJson(context: Context, fileName: String): String {
        val stringBuilder = StringBuilder()
        //获得assets资源管理器
        val assetManager = context.assets
        //使用IO流读取json文件内容
        try {
            val bufferedReader = BufferedReader(
                InputStreamReader(
                    assetManager.open(fileName), "utf-8"
                )
            )
            var line: String?
            while (bufferedReader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }

}